package com.efounder.chat.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.model.RefreshChatItemEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

import static com.efounder.chat.service.SystemInfoService.CHATITEMLIST;
import static com.efounder.chat.service.SystemInfoService.CHATLISTMAP;

/**
 * Created by yqs on 2017/3/24.
 */

public class ChatListHelper {
    private final static String TAG = "ChatListHelper";
    private Context mContext;

    private SimpleDateFormat dateFormat;
    private Handler mainHandler;
    private volatile static ChatListHelper chatListHelper;
    //用户自己的imid
    private static int mySelfUserId;

    /**
     * 置顶index记录
     */
    private static AtomicInteger topIndex = new AtomicInteger(-1);

    public static AtomicInteger getTopIndex() {
        return topIndex;
    }

    /**
     * 加1后返回
     *
     * @return
     */
    public static int topIndexIncrement() {
        return topIndex.incrementAndGet();
    }

    /**
     * 减去1后返回
     *
     * @return
     */
    public static int topIndexDecrement() {
        return topIndex.decrementAndGet();
    }

    public static ChatListHelper getInstance(Context mContext) {
        if (chatListHelper == null) {
            synchronized (ChatListHelper.class) {
                if (chatListHelper == null) {
                    chatListHelper = new ChatListHelper(mContext);
                }
            }
        }
        try {
            mySelfUserId = Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chatListHelper;
    }

    public static void release() {
        chatListHelper = null;
    }

    private ChatListHelper(Context context) {
        mContext = context;
        dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
        mainHandler = new Handler(Looper.getMainLooper());
    }


    public synchronized void initData() {
        List<ChatListItem> lists = WeChatDBManager.getInstance().getAllChatList();
        CHATITEMLIST.clear();
        CHATLISTMAP.clear();
//        TOPINDEX = -1;
        getTopIndex().set(-1);
        Iterator<ChatListItem> iterator = lists.iterator();
        while (iterator.hasNext()) {
            ChatListItem chatListItem = iterator.next();
            // 将查询出的 chatlist列表放入map
            String key = null;
            if (chatListItem.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL
                    || chatListItem.getChatType() == StructFactory
                    .TO_USER_TYPE_OFFICIAL_ACCOUNT) {
                key = "0" + String.valueOf(chatListItem.getUserId());
            } else {
                key = "1" + String.valueOf(chatListItem.getUserId());
            }

            //处理应用号初始化不显示角标
//            List appIDs = BadgeUtil.appIDs;
            List appIDs = BadgeUtil.handleAppContact(mContext);
            if (appIDs.contains(chatListItem.getUserId() + "")) {
                int unReadCount = 0;
                unReadCount = JFMessageManager.getInstance().getUnReadCount(chatListItem.getUserId(), (byte) chatListItem.getChatType());
                if (unReadCount == 0) {

                    chatListItem.setBadgernum(-1);
                } else {
                    //显示红点
                    chatListItem.setBadgernum(0);
                }
            }

            CHATLISTMAP.put(key, chatListItem);
            if (chatListItem.getIsTop() == true) {
//                TOPINDEX++;
                topIndexIncrement();

            }
        }
        if (lists != null) {
            CHATITEMLIST.addAll(lists);
        }


        sortConversationByLastChatTime(CHATITEMLIST);
        sortConversationByIsTop(CHATITEMLIST);
        //setUnreadCount();
        refreshView();
        BadgeUtil.initBadge();
        //  StickyEvent会 缓存最近的一次黏性事件 参考 ： http://android.jobbole.com/82049/
        EventBus.getDefault().postSticky(new SystemInitOverEvent());
    }


    /**
     * 刷新界面
     */
    private synchronized void refreshView() {
        //通知 ChatListSwipeMenuFragment 刷新
        EventBus.getDefault().post(new RefreshChatItemEvent(0));
    }

    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(
            List<ChatListItem> messageItemsList) {

        Collections.sort(messageItemsList, new Comparator<ChatListItem>() {
            @Override
            public int compare(final ChatListItem msg1, final ChatListItem msg2) {
                if (msg1.getStruct002() == null) {
                    return -1;
                }
                if (msg2.getStruct002() == null) {
                    return 1;
                }
                String chatTime1 = dateFormat.format(msg1.getStruct002()
                        .getLocalTime());
                String chatTime2 = dateFormat.format(msg2.getStruct002()
                        .getLocalTime());

                if (chatTime1.compareTo(chatTime2) == 0) {
                    return 0;
                } else if (chatTime1.compareTo(chatTime2) > 0) {
                    return -1;
                } else {
                    return 1;
                }
            }

        });
    }

    /**
     * 根据是否置顶排序
     *
     * @param
     */
    private void sortConversationByIsTop(
            List<ChatListItem> messageItemsList) {

        Collections.sort(messageItemsList, new Comparator<ChatListItem>() {
            @Override
            public int compare(final ChatListItem msg1, final ChatListItem msg2) {

                if (msg1.getIsTop().compareTo(msg2.getIsTop()) == 0) {
                    return 0;
                } else if (msg1.getIsTop().compareTo(msg2.getIsTop()) > 0) {
                    return -1;
                } else {
                    return 1;
                }
            }

        });
    }

    /**
     * 创建或者更新聊天列表
     * 发送以及接收到的消息都会走这个方法
     *
     * @param imstruct002 消息
     */
    public synchronized void createOrUpdateChatListItem(IMStruct002 imstruct002) {
        ChatListItem chatListItem = null;
        final byte chatType = imstruct002.getToUserType();

        //当前正跟你聊天的人的id 可能是个人id 也可能是 groupid
        int chatUserId = chatType == StructFactory.TO_USER_TYPE_GROUP ? imstruct002
                .getToUserId() : imstruct002.getFromUserId();
        int id = chatUserId;//此id有用处
        if (chatUserId == mySelfUserId) {
            chatUserId = imstruct002.getToUserId();//如果fromid是自己（自己发给别人或者两个设备登陆一个账号，取touserID）
        }
        //用户类型，好友可能是公众号，是群聊的话忽略此类型
        //int userType = WeChatDBManager.getInstance().getOneUserById(chatUserId).getType();

        String key = null;
        if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT || chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            key = "0" + String.valueOf(chatUserId);
        } else {
            key = String.valueOf(chatType) + String.valueOf(chatUserId);
        }
        Log.i(TAG, "拼接的key：" + key);

        chatListItem = CHATLISTMAP.get(key);
        if (chatListItem != null) {
            ChatListItem tempItem = null;
            try {
//                tempItem = (ChatListItem) BeanUtils.cloneBean(chatListItem);
                //深拷贝
                tempItem = (ChatListItem) chatListItem.clone();
            } catch (Exception e) {
                e.printStackTrace();
            }
            final ChatListItem updatingChatListItem = tempItem;
            updatingChatListItem.setLoginUserId(mySelfUserId);
            int unReadCount = 0;
            // 如果是单聊或者应用号消息
            if (chatType == StructFactory.TO_USER_TYPE_PERSONAL || chatType == StructFactory
                    .TO_USER_TYPE_OFFICIAL_ACCOUNT) {
                IMStruct002 im0 = JFMessageManager.getInstance().getLastMessage(chatUserId, (byte) 0);
                if (im0 == null) {
                    Log.i(TAG, "---Lastmessage  is  null ----");
                }
                //设置最后一条消息
                updatingChatListItem.setStruct002(im0);
                //调用方法获取未读消息条数
                unReadCount = JFMessageManager.getInstance().getUnReadCount(chatUserId, (byte) 0);

            } else if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
                IMStruct002 im1 = JFMessageManager.getInstance().getLastMessage(chatUserId, chatType);
                if (im1 == null) {
                    Log.i(TAG, "---Lastmessage  is  null ----");
                }
                updatingChatListItem.setStruct002(im1);
                unReadCount = JFMessageManager.getInstance().getUnReadCount(chatUserId, chatType);

            }
            if (unReadCount == 0) {
                updatingChatListItem.setBadgernum(-1);//-1表示不显示角标
            } else {
                //处理应用号显示红点角标--------
//                List appIDs = BadgeUtil.appIDs;
                List appIDs = BadgeUtil.handleAppContact(mContext);
                if (appIDs.contains(updatingChatListItem.getUserId() + "")) {
                    unReadCount = 0;
                } else {
                    //unReadCount = JFMessageManager.getInstance().getUnReadCount(imstruct002.getFromUserId(), (byte) 0);
                }
                updatingChatListItem.setBadgernum(unReadCount);
            }

            //免打扰群组如果有未读不显示角标 显示红点
            if (chatType == StructFactory.TO_USER_TYPE_GROUP && unReadCount != -1 && updatingChatListItem.getIsBother()) {
                // JFMessageManager.getInstance().unreadZero(chatUserId, StructFactory.TO_USER_TYPE_GROUP);
                //显示0 表示显示红点
                updatingChatListItem.setBadgernum(0);
            }

//            Intent intent = new Intent();
//            intent.putExtra("badgernum", unReadCount);
//            intent.setAction(MSG_NEW_MSG_COMMING);
//            mContext.sendBroadcast(intent);

            //todo 在主线程更新数据源，避免异常出现
            final ChatListItem finalChatListItem = chatListItem;
            final int finalChatUserId = chatUserId;
            final String finalKey = key;
            //先放到map中，在在主线程更新数据
            CHATLISTMAP.put(finalKey, updatingChatListItem);
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                   // Log.e("内存地址helper：", System.identityHashCode(getTopIndex()) + "");

                    if (CHATITEMLIST.contains(finalChatListItem)) {
                        if (finalChatListItem.getIsTop() == true) {
                            CHATITEMLIST.remove(finalChatListItem);
                            CHATITEMLIST.add(0, updatingChatListItem);
                        } else {
                            CHATITEMLIST.remove(finalChatListItem);
                            CHATITEMLIST.add(getTopIndex().get() + 1, updatingChatListItem);
                        }
                    }
                    //EventBus事件
                    if (finalChatUserId != mySelfUserId) {
                        EventBus.getDefault().post(new UpdateBadgeViewEvent(finalChatUserId + "", (byte) chatType));
                    }
                    refreshView();
                }
            });


            WeChatDBManager.getInstance().insertOrUpdateChatList(updatingChatListItem);


        } else {
            //1对方发给我们的消息
            int addType = 1;
            if (id == mySelfUserId) {
                // 如果消息来自自己
                addType = 0;
            }
            try {
                createNewItem(imstruct002, addType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        //EventBus事件
//        if (chatUserId != mySelfUserId) {
//            EventBus.getDefault().post(new UpdateBadgeViewEvent(chatUserId + "", (byte) chatType));
//        }


    }

    /**
     * 如果聊天列表中不存在,生成新的item
     *
     * @param imstruct002
     * @param type        判断你发给对方还是对方发给你，1表示对方发给你，0表示你发给对方
     */
    private synchronized void createNewItem(final IMStruct002 imstruct002, int type) throws Exception {
        Log.i(TAG, "-----生成item----");
        final ChatListItem chatListItem = new ChatListItem();
        chatListItem.setLoginUserId(mySelfUserId);
        chatListItem.setStruct002(imstruct002);

        if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL
                || imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            //单聊
            int chatUserId = type == 0 ? imstruct002.getToUserId() : imstruct002.getFromUserId();
            User user = WeChatDBManager.getInstance().getOneUserById(chatUserId);
            if (user != null) {
                chatListItem.setUserId(chatUserId);
                chatListItem.setUser(user);
                chatListItem.setName(user.getReMark());
                chatListItem.setAvatar(user.getAvatar());
                chatListItem.setIsTop(user.getIsTop());
                chatListItem.setIsBother(user.getIsBother());
                chatListItem.setChatType(ChatTypeUtil.getChatType(user.getId(), imstruct002, mContext));
                completeChatListItem(chatListItem, imstruct002, type);
            }

        } else if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
            //群聊
            int chatGroupId = imstruct002.getToUserId();
            chatListItem.setUserId(chatGroupId);
            Group group = WeChatDBManager.getInstance().getGroup(chatGroupId, false);
            //判断如果groupde名字是groupid，其实就是群组在本地不存在，从服务器取一下
            if (!group.isExist()) {
                try {
                    GetHttpUtil.getGroupById(mContext, imstruct002.getToUserId(), new GetHttpUtil.ReqCallBack<Group>() {
                        @Override
                        public void onReqSuccess(Group group) {
                            ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(group.getGroupId(), 1);
                            if (chatListItem != null) {
                                EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {

                        }
                    }, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (group != null) {
                chatListItem.setName(group.getGroupName());
                chatListItem.setAvatar(group.getAvatar());
                Log.i(TAG, "生成item，打印群组头像" + group.getAvatar());
                chatListItem.setGroup(group);
                chatListItem.setIsTop(group.getIsTop());
                chatListItem.setIsBother(group.getIsBother());
                chatListItem.setChatType(StructFactory.TO_USER_TYPE_GROUP);
                completeChatListItem(chatListItem, imstruct002, type);
            }
        }
    }

    /**
     * 完成新生成的chatlistitem
     *
     * @type 判断你发给对方还是对方发给你，1表示对方发给你，0表示你发给对方
     */
    private synchronized void completeChatListItem(final ChatListItem chatListItem, final IMStruct002 imstruct002, int
            type) {
        int unReadCount = 0;
        int chatUserId;
        if (type == 0) {
            // 我发送给对方
            chatUserId = imstruct002.getToUserId();
            unReadCount = JFMessageManager.getInstance().
                    getUnReadCount(imstruct002.getToUserId(), imstruct002.getToUserType());
        } else {//对方发给我
            if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
                unReadCount = JFMessageManager.getInstance().
                        getUnReadCount(imstruct002.getToUserId(), imstruct002.getToUserType());
                chatUserId = imstruct002.getToUserId();
            } else {
                chatUserId = imstruct002.getFromUserId();
                unReadCount = JFMessageManager.getInstance().getUnReadCount(imstruct002.getFromUserId(), (byte) 0);
            }
        }
        if (unReadCount == 0) {
            chatListItem.setBadgernum(-1);
        } else {
//            List appIDs = BadgeUtil.appIDs;
            List appIDs = BadgeUtil.handleAppContact(mContext);
            //处理应用号不显示角标--------
            if (appIDs.contains(chatListItem.getUserId())) {
                unReadCount = 0;
            }
//            else {
//                unReadCount = JFMessageManager.getInstance().getUnReadCount(imstruct002.getFromUserId(), (byte) 0);
//            }
            chatListItem.setBadgernum(unReadCount);
        }

        //免打扰群组如果有未读不显示角标 显示红点
        if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP && unReadCount != -1
                && chatListItem.getIsBother()) {
            //JFMessageManager.getInstance().unreadZero(chatUserId, StructFactory.TO_USER_TYPE_GROUP);
            //显示0 表示显示红点
            chatListItem.setBadgernum(0);
        }
        Log.i(TAG, "角标-----------" + chatListItem.getBadgernum());


        //放入map
        String newKey = null;
        if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT ||
                imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL) {
            newKey = "0" + String.valueOf(chatListItem.getUserId());
        } else {
            newKey = String.valueOf(imstruct002.getToUserType()) + String.valueOf(chatListItem.getUserId());
        }
        CHATLISTMAP.put(newKey, chatListItem);
        //主线程更新数组
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (chatListItem.getIsTop() == true) {
                    //chatListItem.setIsTop(true);
                    CHATITEMLIST.add(0, chatListItem);
//                    TOPINDEX++;
                    topIndexIncrement();

                } else {
                    //chatListItem.setIsTop(false);
//                    CHATITEMLIST.add(TOPINDEX + 1, chatListItem);
                    CHATITEMLIST.add(getTopIndex().get() + 1, chatListItem);
                }


                WeChatDBManager.getInstance().insertOrUpdateChatList(chatListItem);

                //EventBus事件
                EventBus.getDefault().post(new UpdateBadgeViewEvent(chatListItem.getUserId() + "", (byte) chatListItem.getChatType()));
                //刷新界面
                refreshView();
            }
        });

    }


    /**
     * 获取chatlistitem 唯一key
     *
     * @param chatListItem
     * @return
     */
    public static String getKeyFromChatListItem(ChatListItem chatListItem) {
        String key = null;
        if (chatListItem.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL
                || chatListItem.getChatType() == StructFactory
                .TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            key = "0" + String.valueOf(chatListItem.getUserId());
        } else {
            key = "1" + String.valueOf(chatListItem.getUserId());
        }
        return key;

    }
}





